import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yuejie.Paser;
import com.yuejie.urlparse.UrlParser;


public class Parselinksimple extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public Parselinksimple() {
		super();
	}
	
	/*
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String url="";
		String flv="";
		url = request.getParameter("url");
		url = URLDecoder.decode(url, "UTF-8");
		Paser p = new Paser();
		flv = p.parse(url);
		response.setContentType("text/plain;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(flv);
		out.flush();
		out.close();
	}
	*/
	
	/**
	 * get method
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//返回视频请求url
		getMethod4RequestUrl(request,response);
	}
	
	/**
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	private void getMethod4RequestUrl(HttpServletRequest request,HttpServletResponse response) throws IOException {
		String url = request.getParameter("url");
		url = URLDecoder.decode(url, "UTF-8");
		response.setContentType("text/xml;charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		UrlParser up = new UrlParser();
		List<String[]> realUrlList;
		
		try {
			out.println("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n");
			realUrlList = up.getRealUrlList(url);
			out.println("<video-url>");
			out.println("<sd info='normal'>");
			String[] flvUrls = realUrlList.get(0);
			for(String flvUrl : flvUrls){
				out.println("<seg><![CDATA[" + flvUrl + "]]></seg>");
			}
			out.println("</sd>");
			
			out.println("<hd info='hd'>");
			String[] hdUrls = realUrlList.get(1);
			for(String hdUrl : hdUrls){
				out.println("<seg><![CDATA[" + hdUrl + "]]></seg>");
			}
			out.println("</hd>");
			
			out.println("<hd2 info='ultra hd'>");
			String[] hd2Urls = realUrlList.get(2);
			for(String hd2Url : hd2Urls){
				out.println("<seg><![CDATA[" + hd2Url + "]]></seg>");
			}
			out.println("</hd2>");
			out.println("</video-url>");
		} catch (Exception e) {
			out.println("<error>");
			out.println("<![CDATA[parse failed,please check the url]]>");
			out.println("</error>");
		}
		out.flush();
		out.close();
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	public void init() throws ServletException {
	}
	
	public void destroy() {
		super.destroy(); 
	}
}
